package com.party.core.service.gift.biz;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.activity.Activity;
import com.party.core.model.article.Article;
import com.party.core.model.coupon.Coupon;
import com.party.core.model.gift.Gift;
import com.party.core.model.gift.GiftCoupon;
import com.party.core.model.gift.GiftListOutput;
import com.party.core.model.gift.GiftTarget;
import com.party.core.model.goods.Goods;
import com.party.core.model.system.TargetType;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.article.IArticleService;
import com.party.core.service.coupon.ICouponService;
import com.party.core.service.gift.IGiftCouponService;
import com.party.core.service.gift.IGiftService;
import com.party.core.service.gift.IGiftTargetService;
import com.party.core.service.goods.IGoodsService;
import com.party.core.service.member.IMemberGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author：yifeng
 * @description： 礼包和目标的关系
 * @date：Created in  2017/11/24 下午 14:42
 **/
@Service
public class GiftBizService {
    @Autowired
    private IGiftTargetService giftTargetService;
    @Autowired
    private IGiftCouponService giftCouponService;
    @Autowired
    private IGiftService giftService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ICouponService couponService;
    @Autowired
    private IMemberGroupService memberGroupService;

    /**
     * 批量保存礼包和项目的关系
     *
     * @param targetIds 项目id集合
     * @param gift      礼包
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveOrUpdateWithTarget(String targetIds, Gift gift) throws Exception {
        if (StringUtils.isNotEmpty(targetIds)) {
            for (String targetId : targetIds.split(",")) {
                GiftTarget giftTarget = giftTargetService.getUnique(new GiftTarget(targetId, gift.getId()));
                if (giftTarget == null) {
                    giftTarget = new GiftTarget();
                    giftTarget.setGiftId(gift.getId());
                    giftTarget.setTargetId(targetId);
                }
                giftTarget.setStock(gift.getStock());
                giftTarget.setType(gift.getType());
                giftTarget.setCondition(gift.getCondition());
                giftTarget.setConditionParams(gift.getConditionParams());
                giftTarget.setSalesNum(0L);

                if (StringUtils.isEmpty(giftTarget.getId())) {
                    giftTargetService.insert(giftTarget);
                } else {
                    giftTargetService.update(giftTarget);
                }
            }
        }
        List<String> oldTargetIds = LangUtils.transform(giftTargetService.findByGiftId(gift.getId()), new Function<GiftTarget, String>() {
            @Override
            public String apply(GiftTarget input) {
                return input.getTargetId();
            }
        });
        if (StringUtils.isNotEmpty(targetIds)) {
            List<String> newTargetIds = Lists.newArrayList(targetIds.split(","));
            oldTargetIds.removeAll(newTargetIds);
        }

        for (String targetId : oldTargetIds) {
            giftTargetService.deleteByUnique(new GiftTarget(targetId, gift.getId()));
        }
    }

    /**
     * 批量保存礼包和项目的关系
     *
     * @param giftIds  礼包id集合
     * @param targetId 项目id
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveOrUpdateWithTarget(String giftIds, String targetId) throws Exception {
        if (StringUtils.isNotEmpty(giftIds)) {
            for (String giftId : giftIds.split(",")) {
                Gift gift = giftService.get(giftId);
                GiftTarget giftTarget = giftTargetService.getUnique(new GiftTarget(targetId, gift.getId()));
                if (giftTarget == null) {
                    giftTarget = new GiftTarget();
                    giftTarget.setGiftId(gift.getId());
                    giftTarget.setTargetId(targetId);
                }
                giftTarget.setStock(gift.getStock());
                giftTarget.setType(gift.getType());
                giftTarget.setCondition(gift.getCondition());
                giftTarget.setConditionParams(gift.getConditionParams());
                giftTarget.setSalesNum(0L);

                if (StringUtils.isEmpty(giftTarget.getId())) {
                    giftTargetService.insert(giftTarget);
                } else {
                    giftTargetService.update(giftTarget);
                }
            }
        }
        List<String> oldGiftIds = LangUtils.transform(giftTargetService.findByTargetId(targetId), new Function<GiftTarget, String>() {
            @Override
            public String apply(GiftTarget input) {
                return input.getGiftId();
            }
        });
        if (StringUtils.isNotEmpty(giftIds)) {
            List<String> newGiftIds = Lists.newArrayList(giftIds.split(","));
            oldGiftIds.removeAll(newGiftIds);
        }

        for (String giftId : oldGiftIds) {
            giftTargetService.deleteByUnique(new GiftTarget(targetId, giftId));
        }
    }

    /**
     * 获取项目名称
     *
     * @param type     礼包类型
     * @param targetId 项目id
     * @return
     */
    public String getTargetName(String type, String targetId) {
        String targetName = "";
        if (type.equals(TargetType.ZC_ACTIVITY.getCode()) || type.equals(TargetType.ACTIVITY.getCode())) {
            Activity activity = activityService.get(targetId);
            if (activity != null) {
                targetName = activity.getTitle();
            }
        } else if (type.equals(TargetType.ARTICLE.getCode())) {
            Article article = articleService.get(targetId);
            if (article != null) {
                targetName = article.getTitle();
            }
        } else if (type.equals(TargetType.GOODS.getCode())) {
            Goods goods = goodsService.get(targetId);
            if (goods != null) {
                targetName = goods.getTitle();
            }
        }
        return targetName;
    }

    /**
     * 获取项目发布者名称
     *
     * @param type     礼包类型
     * @param targetId 项目id
     * @return
     */
    public String getTargetAuthor(String type, String targetId) {
        String authorId = "";
        if (type.equals(TargetType.ZC_ACTIVITY.getCode()) || type.equals(TargetType.ACTIVITY.getCode())) {
            Activity activity = activityService.get(targetId);
            if (activity != null) {
                authorId = activity.getMember();
            }
        } else if (type.equals(TargetType.ARTICLE.getCode())) {
            Article article = articleService.get(targetId);
            if (article != null) {
                authorId = article.getMemberId();
            }
        } else if (type.equals(TargetType.GOODS.getCode())) {
            Goods goods = goodsService.get(targetId);
            if (goods != null) {
                authorId = goods.getMemberId();
            }
        }
        if (StringUtils.isNotEmpty(authorId)) {
            return memberGroupService.get(authorId).getRealname();
        } else {
            return "";
        }
    }

    /**
     * 保存礼包和票券关系
     *
     * @param couponIds 票券id
     * @param gift      礼包
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public synchronized void saveOrUpdateWithCoupon(String couponIds, GiftListOutput gift, Long oldStock) throws Exception {
        if (StringUtils.isNotEmpty(couponIds)) {
            Long allotNum = gift.getStock();
            if (gift.getSalesNum() != null) {
                allotNum -= gift.getSalesNum();
            }
            for (String couponId : couponIds.split(",")) {
                // 更新已分配数量
                Coupon coupon = couponService.get(couponId);
                Long salesNum = giftCouponService.getStockByCouponId(couponId);

                if (StringUtils.isNotEmpty(gift.getId())) {
                    oldStock =  oldStock == null ? 0L : oldStock;
                    // 编辑情况
                    if ((salesNum - oldStock) + gift.getStock() > coupon.getStock()) {
                        throw new BusinessException("票券库存不足");
                    }
                } else {
                    // 新增情况
                    if (salesNum + gift.getStock() > coupon.getStock()) {
                        throw new BusinessException("票券库存不足");
                    }
                }

                GiftCoupon giftCoupon = giftCouponService.getUnique(new GiftCoupon(gift.getId(), couponId));
                if (giftCoupon == null) {
                    giftCoupon = new GiftCoupon();
                    giftCoupon.setGiftId(gift.getId());
                    giftCoupon.setCouponId(couponId);
                    giftCoupon.setAllotNum(allotNum);
                    giftCouponService.insert(giftCoupon);
                } else {
                    giftCoupon.setAllotNum(allotNum);
                    giftCouponService.update(giftCoupon);
                }

                salesNum = giftCouponService.getStockByCouponId(couponId);

                // 更新已分配数量
                if (coupon.getAllotNum() == null) {
                    coupon.setAllotNum(gift.getStock());
                } else {
                    coupon.setAllotNum(salesNum);
                }
                couponService.update(coupon);
            }
        }

        List<String> oldCouponIds = LangUtils.transform(giftCouponService.findByGiftId(gift.getId()), new Function<GiftCoupon, String>() {
            @Override
            public String apply(GiftCoupon input) {
                return input.getCouponId();
            }
        });

        if (StringUtils.isNotEmpty(couponIds)) {
            List<String> newCouponIds = Lists.newArrayList(couponIds.split(","));
            oldCouponIds.removeAll(newCouponIds);
        }
        for (String couponId : oldCouponIds) {
            giftCouponService.deleteByUnique(new GiftCoupon(gift.getId(), couponId));

            Coupon coupon = couponService.get(couponId);
            Long stock = giftCouponService.getStockByCouponId(couponId);
            coupon.setAllotNum(stock);
            couponService.update(coupon);
        }
    }

    /**
     * 截取字符串
     *
     * @param str
     * @return
     */
    public String subString(String str) {
        if (StringUtils.isNotEmpty(str)) {
            return str.substring(0, str.length() - 1);
        }
        return str;
    }
}
